import Vue from 'vue'
import VueRouter from 'vue-router'
// import RegisterPage from '@/views/Register.vue'
// import LoginPage from '@/views/Login.vue'
import Layout from '@/views/Layout.vue'
import { getToken } from '@/utils/storage'
Vue.use(VueRouter)

const routes = [
  {
    path: '/register',
    component: () => import('@/views/Register.vue')
  },
  {
    path: '/login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/article', component: () => import('@/views/Article.vue') },
      { path: '/collect', component: () => import('@/views/Collect.vue') },
      { path: '/like', component: () => import('@/views/Like.vue') },
      { path: '/user', component: () => import('@/views/User.vue') }
    ]
  },
  {
    path: '/detail',
    component: () => import('@/views/Detail.vue')
  }
]

const router = new VueRouter({
  routes
})
// to去哪儿 from 来自哪里 next 下一步
// 白名单
// next() 放行 next('path') 跳转
const whiteList = ['/register', '/login']
// 路由守卫 每个路由切换都会进来
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    next()// 放行
  } else {
    if (whiteList.includes(to.path)) {
      next()// 放行
    } else {
      next('/login')// 跳转到登录页
    }
  }
})

export default router
